﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

using CommunityServer.Components;
using CommunityServer.Controls;

using Control=CSLive.ControlPanel.Editor.Control;

namespace CSLive.Controls
{
    public class UserMap : WrappedContentBase, ICSLiveControl
    {
        private User _user;

        [Bindable( true )]
        [DefaultValue( "200px" )]
        [Localizable( true )]
        public Unit Width
        {
            get { return ( ViewState[ "Width" ] == null ) ? Unit.Parse( "200px" ) : ( Unit ) ViewState[ "Width" ]; }
            set { ViewState[ "Width" ] = value; }
        }

        [Bindable( true )]
        [DefaultValue( "200px" )]
        [Localizable( true )]
        public Unit Height
        {
            get { return ( ViewState[ "Height" ] == null ) ? Unit.Parse( "200px" ) : ( Unit ) ViewState[ "Height" ]; }
            set { ViewState[ "Height" ] = value; }
        }

        [Bindable( true )]
        [DefaultValue( "" )]
        [Localizable( true )]
        public string Style
        {
            get { return ( ViewState[ "Style" ] == null ) ? "" : ( string ) ViewState[ "Style" ]; }
            set { ViewState[ "Style" ] = value; }
        }

        public override object DataSource
        {
            get
            {
                if ( _user == null ) _user = CSControlUtility.Instance().GetCurrentUser( this );
                return _user;
            }
            set
            {
                if ( value is User ) _user = value as User;
                else throw new InvalidCastException( "DataSource must be a valid User" );
            }
        }

        #region ICSLiveControl Members

        public Dictionary< string, Control > EditorControls
        {
            get
            {
                var dictionary = new Dictionary< string, Control >
                                     {
                                         {
                                             "User's Profile Location Map", new Control( "User's Profile Location Map",
                                                                                         "Displays the Current Location of the User (Location)",
                                                                                         false,
                                                                                         "<CSLive:UserMap Tag=\"Li\" Width=\"100%\" runat=\"server\"><LeaderTemplate><li style=\"font-weight: bold;\"><CSControl:UserData runat=\"server\" Property=\"DisplayName\" />'s Location: </li></LeaderTemplate></CSLive:UserMap>" )
                                             }
                                     };
                return dictionary;
            }
        }

        public string Name
        {
            get { return "User Map"; }
        }

        public Uri DocsUri
        {
            get { return new Uri( "http://communityserverlive.com/controls/user-maps/default.aspx" ); }
        }

        public string Description
        {
            get { return "Displays a Live Map of the location of the current user"; }
        }

        public string Group
        {
            get { return "Live Maps"; }
        }

        #endregion

        protected override void OnLoad( EventArgs e )
        {
            if ( !Page.ClientScript.IsClientScriptIncludeRegistered( "livemapcontroljs" ) )
                Page.ClientScript.RegisterClientScriptInclude( "livemapcontroljs", "http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1" );

            if ( !Page.ClientScript.IsClientScriptBlockRegistered( "onloadeventhandler" ) )
                Page.ClientScript.RegisterClientScriptBlock( GetType(), "onloadeventhandler", "function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { if (oldonload) { oldonload(); } func(); } } }", true );
        }

        protected override void BindDefaultContent( System.Web.UI.Control control, IDataItemContainer dataItemContainer )
        {
            var main = new HtmlGenericControl( "div" );
            main.Attributes.Add( "style", string.Format( "position: relative; width: {0}; height: {1}; {2}", Width, Height, Style ) );
            main.ID = "map";
            control.Controls.Add( main );
            control.Controls.Add( new LiteralControl( "\n                     " ) );
            var script = new HtmlGenericControl( "script" );
            script.Attributes.Add( "type", "text/javascript" );
            var sb = new StringBuilder();
            sb.AppendLine( "" );
            sb.AppendLine( "         var map" + control.ClientID + " = null;" );
            sb.AppendLine( "         function loadMap" + control.ClientID + "() {" );
            sb.AppendLine( "            map" + control.ClientID + " = new VEMap('" + main.ClientID + "');" );
            sb.AppendLine( "            map" + control.ClientID + ".SetDashboardSize(VEDashboardSize.Tiny);" );
            sb.AppendLine( "            map" + control.ClientID + ".LoadMap();" );
            sb.AppendLine( "            map" + control.ClientID + ".SetMapStyle(VEMapStyle.Hybrid);" );
            sb.AppendLine( "            map" + control.ClientID + ".Find(null, '" + _user.Profile.Location + "');" );
            sb.AppendLine( "            setTimeout('addPushPin();', 1000);" );
            sb.AppendLine( "         }" );
            if ( string.IsNullOrEmpty( _user.Profile.Location ) ) AutomatedVisible = false;
            sb.AppendLine( "         function addPushPin() {" );
            sb.AppendLine( "            var center = map" + control.ClientID + ".GetCenter();" );
            sb.AppendLine( "            center = map" + control.ClientID + ".GetCenter();" );
            sb.AppendLine( "            var shape = new VEShape(VEShapeType.Pushpin, center);" );
            sb.AppendLine( "            shape.SetTitle(\"" + _user.DisplayName + "\'s Location\");" );
            sb.AppendLine( "            shape.SetDescription('" + _user.DisplayName + " is Located in " + _user.Profile.Location + "');" );
            sb.AppendLine( "            map" + control.ClientID + ".AddShape(shape);" );
            sb.AppendLine( "            map" + control.ClientID + ".SetZoomLevel(14);" );
            sb.AppendLine( "         }" );
            sb.AppendLine( "         addLoadEvent(loadMap" + control.ClientID + ");" );
            script.InnerHtml = sb.ToString();
            control.Controls.Add( script );
        }
    }
}